package com.fjec.activity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjec.activity.entity.BizActivitySeckillUser;
import com.fjec.activity.service.IRPCService;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.SpecialMapUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fjec.activity.service.IBizActivitySeckillUserService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 006.秒杀活动用户参与表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-09-18
 */
@RestController
@RequestMapping("")
public class BizActivitySeckillUserController {

    @Resource
    private IBizActivitySeckillUserService service;

    @Autowired
    private IRPCService rpcService;

    /**
     * 查询当前用户秒杀结果
     * @param secKillId
     * @return
     */
    @GetMapping("/y/seckillUserGift/gotGiftInfo")
    public JsonResult gotGiftInfo(Long secKillId) {
        Long userId = AccountInfo.getUserId();
        if (userId == null)
            return JsonResult.FAILURE;

        List<Map<String, Object>> userGiftInfo = service.listMaps(new QueryWrapper<BizActivitySeckillUser>()
                                                                        .eq("UserId", userId)
                                                                        .eq("SeckillId", secKillId)
                                                                        .orderByDesc("CreateTime"));
        if (userGiftInfo.size() == 0)
            return JsonResult.FAILURE;

        Map<String, Object> result = userGiftInfo.get(0);
        if (MapUtils.getLong(result, "GiftId") == 0 || MapUtils.getLong(result, "GiftNum") == 0) {
            return JsonResult.success()
                    .code(EnumSysCode.MSG_6007.getCode())
                    .message(EnumSysCode.MSG_6007.getMsg())
                    .build();
        }

        List<Map<String, Object>> giftInfos = rpcService.getGiftInfo(3);
        final Long giftId = MapUtils.getLong(result, "GiftId");
        Optional<Map<String, Object>> giftInfo = giftInfos.stream().filter(info -> MapUtils.getLong(info, "Id").equals(giftId)).findFirst();
        if (giftInfo.isPresent()) {
            Map<String, Object> g = giftInfo.get();
            result.put("giftName", MapUtils.getString(g, "ServName"));
            result.put("amount", MapUtils.getInteger(g, "Amount"));
        }

        return JsonResult.success().data(SpecialMapUtil.lowKey(result)).build();
    }
}
